package com.ysh.smartplatform.security.handlers;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  



import com.ysh.smartplatform.cache.RoleCache;
import com.ysh.smartplatform.pojo.BaseUser;
import com.ysh.smartplatform.pojo.Menu;
import com.ysh.smartplatform.pojo.Role;
import com.ysh.smartplatform.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Jackiechan on 2022/9/15 15:14
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RoleService roleService;

    private RoleCache roleCache;

    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //获取到用户所有的角色和权限,重新设置给用户
        //获取到当前登录的用户
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        Long userId = baseUser.getuId();
        //获取到所有的角色,这里面都是当前用户有的角色
        List<Role> roleList = roleService.findRolesByUserId(userId);
        //我们还需要根据角色的id查询到所有的menu数据
        ///但是我们的rolecache中存放了一份包含有所有menu的role数据,所以我们就当前用户有哪个role我们就去缓存中重新拿这个role对应的数据,然后保存起来就可以了
        roleList = roleList.stream().map(role -> roleCache.get(role.getRoleId())).collect(Collectors.toList());
        //这个是方便我们自己用的,和security没有关系
        baseUser.setRoleList(roleList);
        //重新告诉spring security当前用户的权限
        List<SimpleGrantedAuthority> authorityList = roleList.stream().flatMap(role -> role.getMenuList().stream()).map(Menu::getPerms).filter(s -> StringUtils.hasText(s)).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //重新生成用户的权限数据,然后返回给用户
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(baseUser, baseUser.getPassword(),authorityList );
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        super.onAuthenticationSuccess(request, response, authentication);
    }
}
